<template>
    <div class="app_market_bg"></div>
    <section class="card_con">
        <div class="card_title">客易达应用服务</div>
        <div class="card_list" :size="30">
            <el-skeleton animated :loading="loading">
                <template #template>
                    <appSkeletonTemp></appSkeletonTemp>
                </template>
                <el-card v-for="item in card.list" :key="item.id" shadow="hover" class="box_card">
                    <img :src="item.icon" alt="" class="card_item_image" />
                    <div class="card_bottom">
                        <span class="item_card_tit">{{ item.name }}</span>
                        <el-popover v-if="item.desc.length > 30" placement="top" :width="300" trigger="hover">
                            <template #reference>
                                <div class="item_card_desc">{{ item.desc }}</div>
                            </template>
                            <template #default>
                                <div class="item_card_desc">{{ item.desc }}</div>
                            </template>
                        </el-popover>
                        <div v-else class="item_card_desc">{{ item.desc }}</div>
                        <div class="btn_bottom">
                            <el-button
                                v-if="item.has_app === 0"
                                v-auth="'IMMEDIATELY_ADD'"
                                type="primary"
                                class="add_btn"
                                @click="addApp(item)">
                                立即添加
                            </el-button>
                            <el-button
                                v-else
                                v-auth="'IMMEDIATELY_USE'"
                                type="primary"
                                class="add_btn"
                                @click="goApp(item)">
                                立即使用
                            </el-button>
                        </div>
                    </div>
                </el-card>
            </el-skeleton>
        </div>
        <div class="card_title">第三方应用集成</div>
        <div class="card_list" :size="30">
            <el-skeleton animated :loading="loading">
                <template #template>
                    <appSkeletonTemp></appSkeletonTemp>
                </template>
                <!-- 接口 -->
                <el-card v-for="item in card.third" :key="item.id" shadow="hover" class="box_card">
                    <img :src="item.icon" alt="" class="card_item_image" />
                    <div class="card_bottom">
                        <span class="item_card_tit">{{ item.name }}</span>
                        <el-popover v-if="item.desc.length > 30" placement="top" :width="300" trigger="hover">
                            <template #reference>
                                <div class="item_card_desc">{{ item.desc }}</div>
                            </template>
                            <template #default>
                                <div class="item_card_desc">{{ item.desc }}</div>
                            </template>
                        </el-popover>
                        <div v-else class="item_card_desc">{{ item.desc }}</div>
                        <div class="btn_bottom">
                            <el-button
                                v-if="item.is_add == 0"
                                v-auth="'IMMEDIATELY_ADD'"
                                type="primary"
                                class="add_btn"
                                :disabled="item?.is_gray"
                                @click="addApp(item)">
                                立即添加
                            </el-button>
                            <el-button v-else type="primary" class="add_btn" @click="goApp(item)">立即使用</el-button>
                        </div>
                    </div>
                </el-card>
            </el-skeleton>
        </div>
    </section>
    <!-- 展示体验延期二维码 -->
    <el-dialog v-model="changePackage" title="企业专属顾问" width="25%" center>
        <div class="qwQrCode">
            <img src="https://static.scrm.keyid.cn/assets/images/global/service.png" alt="" />
        </div>
        <p style="text-align: center">扫码添加企微顾问，开通使用！</p>
    </el-dialog>
    <!-- 添加客易达会员通应用二次确认弹窗 -->
    <memberPassDialog v-model="kydMemberPassVisabled" @submit="toAddMemberPass" />
</template>
<script setup lang="ts">
import { reactive, onMounted, ref } from 'vue';
import router from '@/router';
import { store } from '@/store';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getAppList, addEnterpriseApp, getLink, getAuthStatus, getThirdAppList, addThird } from '@/api/appmarket';
import memberPassDialog from './components/memberPassDialog.vue';
import appSkeletonTemp from '../components/appSkeletonTemp.vue';

const changePackage = ref(false);

const card = reactive({
    list: [
        {
            id: 1,
            name: '',
            desc: '',
            icon: '',
            type: 1,
            kyd_type: 1, // 客易达类型：1-代开发，2-客易达电商，3-自营店铺，4客易达会员通
            homepage: '',
            has_app: 1
        }
    ],
    third: [
        {
            id: 1,
            name: '',
            desc: '',
            icon: '',
            type: 1,
            homepage: '',
            has_app: 1,
            is_add: 1,
            is_gray: 0 // 是否置灰不可选
        }
    ]
});

onMounted(() => {
    // 获取应用列表
    renderAppList();
});

const loading = ref(false); // 骨架屏loading
// 获取应用列表
const renderAppList = async () => {
    try {
        loading.value = true;
        const data = await getAppList();
        const third = await getThirdAppList();
        card.list = data;
        card.third = third;
    } finally {
        loading.value = false;
    }
};
const APP_DATA: any = null;

/* ----------------------------客易达会员通-start---------------------------- */
const kydMemberPassVisabled = ref(false); // 弹窗显隐
let kydMemberPassData: any = null; // 缓存一个客易达会员通的数据

// 前置判断是否是客易达会员通应用做拦截, 如果是，则返回true阻断
const beforeAddApp = (data: any) => {
    if (data.kyd_type === 4) {
        kydMemberPassData = data;
        kydMemberPassVisabled.value = true;
        return true;
    }
    return false;
};
// 添加客易达会员通应用
const toAddMemberPass = () => {
    handleAddEnterpriseApp(kydMemberPassData);
};
/* ----------------------------客易达会员通-end---------------------------- */

const addApp = async (data: any) => {
    if (beforeAddApp(data)) return; // 拦截客易达会员通做单独处理

    const { suite_auth } = await getAuthStatus();
    if (data.type == 2) {
        // 查看服务商授权
        if (suite_auth) {
            handleAddEnterpriseApp(data);
        } else {
            ElMessageBox.confirm('您还没有授权客易达SCRM管理您的企业微信<br/>请授权后再添加应用！', {
                dangerouslyUseHTMLString: true,
                center: true
            }).then(() => {
                doAuthorization();
            });
        }
    } else {
        if (data.type == 4) {
            if ([1, 2, 3, 4, 5, 6, 7, 8].includes(data.third_type)) {
                addThird({ app_id: data.id }).then(() => {
                    ElMessage.success('添加成功');
                    router.push('/appmarket/myapp');
                });
            } else {
                changePackage.value = true;
            }
        } else {
            handleAddEnterpriseApp(data);
        }
    }
};

const createLinkEle = (linkHref: string) => {
    let a: HTMLAnchorElement | null = document.createElement('a');
    a.href = linkHref;
    a.target = '_blank';
    a.click();
    a = null;
};

// 去授权
const doAuthorization = async () => {
    const currentCorp = store.getters['user/getCurrentCorp'] || '';
    const params = {
        new_corp_id: currentCorp,
        callback_front_url: location.href
    };
    const resUrl = await getLink(params);
    createLinkEle(resUrl.link);
};

// 添加企业应用
const handleAddEnterpriseApp = async (data: any) => {
    await addEnterpriseApp({ app_id: data.id });
    ElMessage.success('添加成功');
    goApp(data);
};

const goApp = (data: any) => {
    router.push('/appmarket/myapp');
};
</script>

<style scoped lang="scss">
@import '../index.scss';
.app_market_bg {
    height: 140px;
    width: 100%;
    margin-bottom: 16px;
    background-image: url('/static/app/app_title_bg.png');
    background-size: cover;
}
</style>
